package com.lottery.ruok.lottrey.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.MyApplication;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.CountTimesRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetProfileRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.Base64Utils;
import utils.RSAUtils;
import utils.Utils;

//import com.lottery.ruok.lottrey.retrofitModule.ChangeIP;

//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.security.PrivateKey;
//import java.util.ArrayList;
//import okhttp3.Call;
//import okhttp3.Callback;
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;
//import utils.Base64Utils;
//import utils.RSAUtils;

public class WelcomeActivity extends BaseActivity {
    private String mLocationX = null;
    private String mLocationY = null;
    private Disposable mTimeObserver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

//        if(UserInfo.getQuickUrl().equals("")){
//            UserInfo.setQuickDomain("https://" + BuildConfig.DOMAIN_URL + String.format("/cn/cgi/app/0/%s/", MyApplication.UUID));
//
//            ChangeIP.checkIPs(new ChangeIP.AfterIPAction() {
//                @Override
//                public void doAction() {
//                    init();
//                }
//            });
//        } else {
//            init();
//        }

        init();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        getLocation();
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        countTimes();
    }

    private void init() {
//        if(UserInfo.getLocalUrl().equals("")){
//            UserInfo.setLocalUrl(Common.APP_URL);
//        }

        if (UserInfo.getVersionCode() < Utils.getVersionCode()) {
            UserInfo.setVersionCode(Utils.getVersionCode());
            UserInfo.setFirstStart(true);
        }

        mTimeObserver = Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@NonNull Long aLong) {
                        if (!UserInfo.getToken().equals("")) {
                            synData();
                        } else {//未登录直接绑定一个固定的用户名和密码
                            goToMainInterface();
                        }
                    }
                });

        Common.UserAgentString = String.format("%s,Android %s,%s,%s,%s", Utils.getVersionCode() + "", android.os.Build.MODEL, Build.VERSION.RELEASE, mLocationX, mLocationY);
        if (!UserInfo.getToken().equals("")) {
            PermissionGen.with(this)
                    .addRequestCode(100)
                    .permissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                    .request();
        }
    }

    private void countTimes() {//统计次数
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(CountTimesRequest.class)
                .getResult(Common.UserAgentString, UserInfo.getToken(), mLocationX, mLocationY, BuildConfig.app_name, Utils.getVersionCode() + "", Build.VERSION.RELEASE)
                .compose(RxHelper.handleResult())
                .subscribeWith(new RxSubscribe<Object>(this) {
                    @Override
                    protected void _onNext(Object o) {

                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void getLocation() {
        LocationManager locationManager;
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(location != null){
            mLocationX = location.getLatitude() + "";
            mLocationY = location.getLongitude() + "";
        }
        countTimes();
    }

    private void synData(){
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetProfileRequest.class).getResult(UserInfo.getToken())
                .compose(RxHelper.<GetProfileResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetProfileResponse>(this) {
                    @Override
                    protected void _onNext(GetProfileResponse g) {
                        UserInfo.setIsTest(g.getUser().getIs_test());
                        UserInfo.setIsTry(g.getUser().getIs_try());
                        UserInfo.setUsername(g.getUser().getUsername());
                        UserInfo.setNickname(g.getUser().getNickname());
                        UserInfo.setAccount(g.getUser().getAccount());
                        UserInfo.setMobilePhone(g.getUser().getMobile_phone());
                        UserInfo.setChatroom_block(g.getUser().getChatroom_block());
                        if(g.getUser().getAvatar() != null) {
                            UserInfo.setAvatar(g.getUser().getAvatar());
                        }
                        Common.today_profit = g.getToday_lostwin();

                        goToMainInterface();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        goToMainInterface();
                    }
                });
        disposables.add(disposableObserver);
    }

    private void goToMainInterface(){
        if(UserInfo.getFirstStart()){
            startActivity(new Intent(WelcomeActivity.this, FirstShowActivity.class));
        } else {
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(mTimeObserver != null){
            mTimeObserver.dispose();
            mTimeObserver = null;
        }
    }


}